﻿/**
 * Websocket通知模块
 * @param {any} url
 * @param {any} clientIP
 */
function Notifier(url, clientIP, localStorageManager) {
    this.socket = new WebSocket(url);
    this.clientIP = clientIP;
    this.localStorageManager = localStorageManager;
};

Notifier.prototype = {
    init: function () {
        var self = this;
        this.socket.onopen = function (ev) {
            console.log(this.url + '已连接！' + Math.random());
            self.localStorageManager.removeServerShutdown()
            var intervalId = setInterval(function () {
                if (self.clientIP && self.socket.readyState == WebSocket.OPEN) {
                    self.socket.send('Ping-' + self.clientIP);
                }

                if (self.socket.readyState == WebSocket.CLOSED
                    || self.socket.readyState == WebSocket.CLOSING) {
                    clearInterval(intervalId);
                }
            }, 1000);
        };

        this.socket.onclose = function (ev) {
            console.log('和矩阵服务的连接中断！');
            self.localStorageManager.setServerShutdown();
        };
    },
    onmessage: function (handler) {
        this.socket.onmessage = handler;
    },
    close: function () {
        if (this.socket.readyState != WebSocket.CLOSED
            && this.socket.readyState != WebSocket.CLOSING) {
            this.socket.close();
        }
    },
    ping: function (clientIP) {
        if (clientIP) {
            this.socket.send('Ping-' + clientIP);
        }
    }
};